package com.hframe.http.client;

import com.google.gson.JsonElement;
import com.hframe.Json.DataToJson;
import com.hframe.data.DRef;
import org.apache.log4j.Logger;

import java.net.HttpURLConnection;

/**
 * Created by heqian on 12/7/16.
 */
public class DataParam implements HttpParam {
    private static Logger log = Logger.getLogger(DataParam.class);
    protected String contentType = "application/explain;charset=UTF-8";
    protected byte[] buffer = null;

    public DataParam(DRef<? extends DRef> data, String... outKey) {
        JsonElement json = DataToJson.convert(data, outKey);
        try {
            this.buffer = json.toString().getBytes("UTF-8");
        } catch (Exception e) {
            log.error( e.getMessage(), e);
        }
        System.out.println("DataParam" + json.toString());
    }

    @Override
    public void init(HttpURLConnection conn) {
        conn.setRequestProperty("Content-type", contentType);
    }


    @Override
    public long getDataLenght() {
        return buffer.length;
    }

    @Override
    public String getUrlString() {
        return "";
    }

    @Override
    public boolean read(HttpURLConnection connection, Write write) throws Exception {
        if (null == write)
            return false;

        writeBuffer(write, buffer);
        return true;
    }

    protected void writeBuffer(Write write, byte[] data) throws Exception {
        for (int index = 0; index < data.length; index += 4096) {
            write.write(data, index, data.length - index > 4096 ? 4096 : data.length - index);
        }
    }
}
